<template>
  <van-button type="primary" @click="takePhoto">拍照</van-button>
</template>

<script setup>
import { onMounted, reactive, toRefs, ref } from 'vue'
import { postData } from '@/request/request.js'
import { useRoute, useRouter } from 'vue-router'
let router = useRouter()
let route = useRoute()
//let query = route.query
// localStorage.setItem('user_id', query.user_id)
// localStorage.setItem('access_token', query.access_token)
// localStorage.setItem('open_id', query.open_id)
// localStorage.setItem('currentPath', query.currentPath)

let msg = ref('')
const carriedUserid = ref('')

let init = () => {}

let fn_upload = (imageBase64) => {
  let param = {}
  if (imageBase64) {
    if (carriedUserid.value) {
      param = {
        user_id: carriedUserid.value,
        image_base64: imageBase64,
        image_ext: 'jpg',
      }
    } else {
      param = {
        user_id: localStorage.getItem('user_id'),
        image_base64: imageBase64,
        image_ext: 'jpg',
      }
    }
    postData('/user/facephoto/base64image/upload', param).then((res) => {
      console.log(res)
    })
  }
}

//拍照
let takePhoto = () => {
  wx &&
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (imgRes) => {
        let localIds = imgRes.localIds
        if (Array.isArray(localIds) && localIds.length) {
          wx &&
            wx.getLocalImgData({
              localId: localIds[0],
              success: (localImgRes) => {
                let localData = localImgRes.localData

                let imageBase64 = localData.replace(
                  'data:image/jpeg;base64,',
                  ''
                )
                let index = localData.indexOf('data:image/jpeg;base64,')
                let len = 'data:image/jpeg;base64,'.length
                if (index === 0) {
                  imageBase64 = imageBase64.substring(len - 1)
                }

                /* if (localData.indexOf('data:image') === 0) {
                  // 苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                  imageBase64 = localData
                } else {
                  // 此处是安卓中的唯一得的坑！在拼接前需要对localData进行换行符的全局替换
                  // 此时一个正常的 base64 图片路径就完美生成赋值到 img 的 src 中了
                  imageBase64 = `data:image/jpeg;base64,${localData.replace(
                    /\n/g,
                    ''
                  )}`
                } */
                imageBase64 && fn_upload(imageBase64)
              },
              fail: (localImgErr) => {
                console.log(localImgErr?.errMsg)
              },
            })
        }
      },
      fail: (imgErr) => {
        console.log(imgErr?.errMsg)
      },
    })
}

onMounted(() => {
  init()
})
</script>

<style scoped></style>
